<script setup>
import { ref } from 'vue'
import { getWhlist } from '@/api/setting'
import { useAdminStore } from '@/stores';
import { getUserListByDeptId, getUserListByWhId, setWhAdmins, delInventory, getWhType, updateWh, addWhType } from '@/api/setting'
const status = ref({
  isAdd: false,
  isEdit: false,
})
const isAddType = ref(false)
const isDrawer = ref(false)
const whlist = ref('')
const whTypeList = ref('')
const doGetWhlist = async () => {
  await getWhlist('all').then(res => {
    if (res.data.success) {
      whlist.value = res.data.data
      console.log('仓库列表：', whlist.value)
    }
  })
}
doGetWhlist()
getWhType().then(res => {
  whTypeList.value = res.data.data
})
const _nodeData = {
  id: null,
  name: null,
  type: null,
  code: null,
  address: null,
  children: null,
  parentId: null,
}
const nodeData = ref({ ..._nodeData })
const whAdminList = ref([])
const userTags = ref([])
const getWhNodeData = async (data) => {
  status.value.isAdd = false
  status.value.isEdit = false
  nodeData.value = data
  console.log(data)
  await getUserListByWhId(data.id).then((res) => {
    whAdminList.value = res.data.data
    console.log(whAdminList.value)
    userTags.value = JSON.parse(JSON.stringify(whAdminList.value))
  })
}
// 新增仓库
const newInvetory = async () => {
  nodeData.value = _nodeData
  status.value.isAdd = true
}
const fatherWh = ref('')
const getAddNodeData = (node) => {
  console.log(node)
  nodeData.value.parentId = node.id
  fatherWh.value = node.name
}
const cancel = () => {
  status.value.isAdd = false
  status.value.isEdit = false
}
const confirm = async () => {
  if (!nodeData.value.name || !nodeData.value.type) {
    ElMessage.error('请完善仓库信息')
    return
  }
  await updateWh(nodeData.value).then(res => {
    if (res.data.success) {
      ElMessage.success(res.data.data)
    }
  })
  status.value.isAdd = false
  status.value.isEdit = false
  await doGetWhlist()
}
// 抽屉页，选择仓库管理员
const adminStore = useAdminStore()
const userList = ref([])
const pageTotal = ref()

// 删除tag中的选择项
const handleTagClose = (tag) => {
  userTags.value.splice(userTags.value.indexOf(tag), 1)
}
// 条件查询
const getDeptNodeData = async (data) => {
  console.log(data.name)
  await getUserListByDeptId(data.id)
    .then((res) => {
      userList.value = res.data.data.records
      pageTotal.value = res.data.data.total
    })
}
// 删除仓库
const doDelInventory = async () => {
  console.log(nodeData.value.children.length === 0)
  if (nodeData.value.children.length === 0) {
    await delInventory(nodeData.value.id).then(res => {
      if (res.data.success) {
        ElMessage.success('删除成功')
      } else {
        ElMessage.error(res.data.data)
      }
    })
  } else {
    ElMessage.error('该仓库下有子仓库，无法删除')
  }
  status.value.isAdd = false
  status.value.isEdit = false
  nodeData.value = { ..._nodeData }
  await doGetWhlist()
}
// 点击表格事件，将点击的行内容增加到userTag中
const tableCellClick = (row) => {
  if (!JSON.stringify(userTags.value).includes(JSON.stringify(row))) {
    userTags.value.push(row)
  } else {
    ElMessage.error('重复选择用户')
  }
}

//
const drawerCanceelClick = () => {
  isDrawer.value = false
  userTags.value = JSON.parse(JSON.stringify(whAdminList.value))
}
const drawerConfirmClick = async () => {
  await setWhAdmins(nodeData.value.id, userTags.value).then(async (res) => {
    await getUserListByWhId(nodeData.value.id).then((res) => {
      whAdminList.value = res.data.data
      userTags.value = JSON.parse(JSON.stringify(whAdminList.value))
    })
    ElMessage.success(res.data.data)
    isDrawer.value = false
  })

}
// 新增类别
const typeName = ref('')
const typeData = ref({
  name: '',
  code: ''
})
const doAddWhType = async () => {
  for (let i in whTypeList.value) {
    if (whTypeList.value[i].name === typeName.value) {
      ElMessage.warning("已有该类别")
      return
    }
  }
  await addWhType(typeData.value).then(async (res) => {
    if (res.data.success) {
      ElMessage.success(res.data.data)
      await getWhType().then(res => {
        whTypeList.value = res.data.data
        typeData.value.name = ''
        typeData.value.code = ''
      })
    }
  })

  // isAddType.value = false
}

</script>

<template>
  <MainContainer ref="mainContainerRef" title="仓库管理">
    <el-row>
      <TreeSlideShow @getNodeData="getWhNodeData" :list="whlist" title="仓库列表">
        <el-button type="primary" size="small" style="width: 40%; " @click="newInvetory">新增仓库</el-button>
      </TreeSlideShow>
      <el-col :span="20" class="right">
        <div>
          <el-text>仓库信息</el-text>
          <el-button size="small" type="primary" style="margin-left: 30px; width: 100px;" @click="status.isEdit = true"
            v-show="nodeData.name !== null && !status.isEdit && !status.isAdd">编辑</el-button>
          <el-button size="small" type="danger" style="margin-left: 30px; width: 100px;" @click="doDelInventory"
            v-show="nodeData.name !== null && status.isEdit">删除</el-button>
        </div>
        <el-form label-width="auto" :disabled="!status.isEdit && !status.isAdd">
          <el-form-item label="仓库名称" required>
            <el-input v-model="nodeData.name"></el-input>
          </el-form-item>
          <el-form-item label="父级选择" v-show="status.isAdd"> <!-- "|| status.isEdit"先不考虑修改腹肌等级，复杂-->
            <el-tree-select :data="whlist" :props="{ children: 'children', label: 'name' }" node-key="id"
              default-expand-all :expand-on-click-node="false" clearable @node-click="getAddNodeData"
              v-model="fatherWh"></el-tree-select>
          </el-form-item>
          <el-form-item label="仓库类别" required>
            <el-select v-model="nodeData.type" :placeholder="nodeData.type">
              <el-option v-for="item in whTypeList" :key="item.id" :label="item.name" :value="item.name"></el-option>
            </el-select>
            <el-button v-show="status.isAdd || status.isEdit" type="primary" style="margin-left: 30px"
              @click="isAddType = true"><el-icon style="margin-right: 10px">
                <Plus />
              </el-icon>新增类别</el-button>
          </el-form-item>
          <el-form-item label="仓库编号">
            <el-input v-model="nodeData.code"></el-input>
          </el-form-item>
          <el-form-item label="仓库地址">
            <el-input v-model="nodeData.address"></el-input>
          </el-form-item>
        </el-form>
        <div v-show="!status.isAdd">
          <el-text>仓库管理员</el-text>
          <el-button size="small" type="primary" style="margin-left: 30px; width: 100px;"
            v-show="nodeData.name !== null && status.isEdit" @click="isDrawer = true">编辑</el-button>
        </div>
        <el-table v-show="!status.isAdd" :data="whAdminList" style="margin-top: 30px;">
          <el-table-column align="center" label-align="center" type="index" label="序号" width="80px"></el-table-column>
          <el-table-column align="center" label-align="center" label="用户名" prop="username"></el-table-column>
          <el-table-column align="center" label-align="center" label="姓名" prop="name"></el-table-column>
          <el-table-column align="center" label-align="center" label="部门" prop="dept"></el-table-column>
          <el-table-column align="center" label-align="center" label="岗位" prop="job"></el-table-column>
          <el-table-column align="center" label-align="center" label="手机号" prop="phone"></el-table-column>
          <el-table-column align="center" label-align="center" label="邮箱" prop="email"></el-table-column>
        </el-table>
        <el-row>
          <div class="bottom">
            <el-button type="primary" v-show="status.isAdd || status.isEdit" @click="confirm">确认</el-button>
            <el-button class="cancel" v-show="status.isAdd || status.isEdit" @click="cancel">取消</el-button>
          </div>
        </el-row>
      </el-col>
    </el-row>

    <el-drawer v-model="isDrawer" direction="rtl" title="编辑仓库管理员" size="70%">
      <el-row style="padding: 20px 10px;">
        <el-text>已选管理员：</el-text>

        <el-tag v-for=" tag in userTags" :key="tag.name" closable type="primary" @close="handleTagClose(tag)">
          {{ tag.name }}
        </el-tag>
      </el-row>
      <el-row>
        <!-- <el-col> -->
        <TreeSlideShow @getNodeData="getDeptNodeData" :list="adminStore.deptList"></TreeSlideShow>
        <!-- </el-col> -->
        <el-col :span="20">
          <el-table ref="userTableRef" :data="userList" @cell-click="tableCellClick">
            <el-table-column header-align="center" align="center" type="index" label="序号" width="100"></el-table-column>
            <el-table-column header-align="center" align="center" label="用户名" prop="username"></el-table-column>
            <el-table-column header-align="center" align="center" label="姓名" prop="name"></el-table-column>
            <el-table-column header-align="center" align="center" label="工号" prop="code"></el-table-column>
            <el-table-column header-align="center" align="center" label="性别">
              <template #default="scope">
                <div>{{ scope.row.gender === '1' ? "男" : "女" }}</div>
              </template>
            </el-table-column>
            <el-table-column header-align="center" align="center" label="手机号" prop="phone"></el-table-column>
            <el-table-column header-align="center" align="center" label="邮箱" prop="email"></el-table-column>
            <el-table-column header-align="center" align="center" label="状态" prop="status">
              <template #default="scope">
                <div>{{ scope.row.status === '1' ? "启用" : "停用" }}</div>
              </template>
            </el-table-column>
            <el-table-column header-align="center" align="center" label="岗位" prop="job"></el-table-column>
          </el-table>
          <div style="display:flex; justify-content:center;">
            <el-pagination layout="prev, pager, next" :total="50" />
          </div>

        </el-col>
      </el-row>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawerCanceelClick">取消</el-button>
          <el-button type="primary" @click="drawerConfirmClick">确认</el-button>
        </div>
      </template>
    </el-drawer>
    <el-dialog v-model="isAddType" title="新增类别">
      <el-divider></el-divider>
      <div>
        <el-text>当前已有类别：</el-text>
        <el-tag v-for="item in whTypeList" :key="item.id" effect="dark" size="large" type="primary"
          style="margin: 8px;">{{
            item.name
          }}</el-tag>
      </div>
      <el-divider border-style="dashed"></el-divider>
      <div>
        <el-text style="line-height: 50px;">新增类别</el-text><br>
        <div style="width:700px; margin: 0 auto;">
          <!-- <span>输入类别名称：</span>
          <el-input v-model="typeName" style="margin:0 20px; width:200px;"></el-input> -->
          <el-form :data="typeData" :inline="true" label-width="auto">
            <el-form-item label="类别名称">
              <el-input v-model="typeData.name"></el-input>
            </el-form-item>
            <el-form-item label="类别代码">
              <el-input v-model="typeData.code"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="doAddWhType">增加</el-button>
            </el-form-item>
          </el-form>

        </div>
        <el-divider border-style="dashed"></el-divider>
      </div>
    </el-dialog>
  </MainContainer>


</template>

<style scoped lang="less">
.left {
  min-height: 80vh;
  border-right: 1px dashed #ccc;

  p {
    margin-left: 20px;
  }

  .search {
    padding: 10px 10px;
    width: 100%;
    border-radius: 10px;
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
}

.right {
  padding-left: 30px;

  .el-form {
    padding: 30px 50px;

    .el-select {
      width: 300px;
    }

    .el-input {
      width: 300px;
    }
  }

  .bottom {
    margin: 20px auto;

    .el-button {
      width: 100px;
    }

  }
}
</style>